package com.hjk.waibao.mj.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hjk.waibao.mj.bean.ApiResult;
import com.hjk.waibao.mj.exception.CustomException;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;

/**
 * @Description
 * @Author hjk
 * @Date 2020/5/6
 **/
public class ExceptionInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation invocation) {
        try {
            invocation.invoke();
        } catch (Exception e) {
            if (e.getCause() instanceof Error) {
                Error error = (Error) e.getCause();
                error.printStackTrace();
                if (StrUtil.isBlankOrUndefined(error.getMessage())) {
                    invocation.getController().renderJson(ApiResult.createFail("系统错误"));
                } else {
                    invocation.getController().renderJson(ApiResult.createFail(error.getMessage()));
                }
            } else {
                Exception causeException = (Exception) e.getCause();
                if (causeException != null && causeException instanceof CustomException) {
                    e = causeException;
                }
                if (e instanceof CustomException) {
                    CustomException customException = (CustomException) e;
                    customException.printStackTrace();
                    invocation.getController().renderJson(ApiResult.createFail(customException.getMessage()));
                } else {
                    e.printStackTrace();
                    if (StrUtil.isBlankOrUndefined(e.getMessage())) {
                        invocation.getController().renderJson(ApiResult.createFail("系统错误"));
                    } else {
                        invocation.getController().renderJson(ApiResult.createFail(e.getMessage()));
                    }
                }
            }
        }
    }
}